<?php
namespace Base\Controller;

use Think\Controller;

class HomeBaseController extends Controller {
	
	public function __construct() {
		$this->_setActionSuccessErrorTpl();
		parent::__construct();
	}
	
	function _initialize() {
		defined('TMPL_PATH') or define("TMPL_PATH", C("SP_TMPL_PATH"));
		$this->assign("siteSetting", getSiteSetting());
		
		if (session('CUSTOMER')) {
			$this->assign("customer", session('CUSTOMER'));
		}
	}
	
	/**
	 * 检查用户登录
	 */
	protected function checkLogin() {
	    $sessionCustomer = session('CUSTOMER');
		if (empty($sessionCustomer)) {
			$this->error(L('NO_LOGIN'), U('Customer/Login/login', array('redirect'=>base64_encode($_SERVER['HTTP_REFERER']))));
		}
	}
	
	/**
	 * 检查用户状态
	 */
	protected function checkCustomerStatus() {
	    $sessionCustomerId = session('CUSTOMER.id');
	    $status = M('Customer')->where(array("id" => $sessionCustomerId))->getField("status");
	    if ($status != 1) {
			if ($status == -1 || $status == -2) {
				$this->error(L('USERNAME_NOT_EXIST_OR_FORBIDDEN'), __ROOT__ . "/");
			} else if ($status == 0 || $status == 2) {
				$this->assign("messageTitle", "账号未认证！");
				$this->error('您还没有通过账号认证，请认证后再使用！', U("Customer/Login/auth"));
			} else if ($status == 3) {
				$this->assign("messageTitle", "等待认证中！");
				$this->error('等待认证中，请通过认证后再进入！');
			}
	    }
	}
	
	/**
	 * 加载模板和页面输出 可以返回输出内容
	 * @access public
	 * @param string $templateFile 模板文件名
	 * @param string $charset 模板输出字符集
	 * @param string $contentType 输出类型
	 * @param string $content 模板输出内容
	 * @return mixed
	 */
	public function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
		parent::display($this->_parseTemplate($templateFile), $charset, $contentType, $content, $prefix);
	}
	
	/**
	 * 获取输出页面内容
	 * 调用内置的模板引擎fetch方法，
	 * @access protected
	 * @param string $templateFile 指定要调用的模板文件
	 * 默认为空 由系统自动定位模板文件
	 * @param string $content 模板输出内容
	 * @param string $prefix 模板缓存前缀*
	 * @return string
	 */
	public function fetch($templateFile='', $content='', $prefix='') {
	    $templateFile = empty($content) ? $this->_parseTemplate($templateFile) : '';
		return parent::fetch($templateFile, $content, $prefix);
	}
	
	/**
	 * 自动定位模板文件
	 * @access protected
	 * @param string $template 模板文件规则
	 * @return string
	 */
	public function _parseTemplate($template = '') {
		$tmpl_path = C("SP_TMPL_PATH");
		define("SP_TMPL_PATH", $tmpl_path);
		if ($this->theme) { // 指定模板主题
		    $theme = $this->theme;
		} else {
		    // 获取当前主题名称
		    $theme = C('SP_DEFAULT_THEME');
		    if (C('TMPL_DETECT_THEME')) {// 自动侦测模板主题
		        $t = C('VAR_TEMPLATE');
		        if (isset($_GET[$t])) {
		            $theme = $_GET[$t];
		        } elseif (cookie('think_template')) {
		            $theme = cookie('think_template');
		        }
		        if (!file_exists($tmpl_path . "/" . $theme)) {
		            $theme = C('SP_DEFAULT_THEME');
		        }
		        cookie('think_template', $theme, 864000);
		    }
		}
		
		$theme_suffix = "";
		$lang_suffix = "_" . LANG_SET;
	    if (C('LANG_SWITCH_ON', null, false) && file_exists($tmpl_path. "/" . $theme . $lang_suffix)) {
	        $theme_suffix = $lang_suffix;
	    }
		$theme = $theme . $theme_suffix;
		C('SP_DEFAULT_THEME', $theme);
		$current_tmpl_path = $tmpl_path . $theme . "/";
		define('THEME_PATH', $current_tmpl_path);								// 获取当前主题的模版路径
		
// 		$cdn_settings=sp_get_option('cdn_settings');
// 		if (!empty($cdn_settings['cdn_static_root'])) {
// 		    $cdn_static_root = rtrim($cdn_settings['cdn_static_root'],'/');
// 		    C("TMPL_PARSE_STRING.__TMPL__", $cdn_static_root."/".$current_tmpl_path);
// 		    C("TMPL_PARSE_STRING.__PUBLIC__", $cdn_static_root."/public");
// 		    C("TMPL_PARSE_STRING.__WEB_ROOT__", $cdn_static_root);
// 		} else {
		    C("TMPL_PARSE_STRING.__TMPL__",__ROOT__."/".$current_tmpl_path);
// 		}
		
		C('SP_VIEW_PATH', $tmpl_path);
		C('DEFAULT_THEME', $theme);
		
		define("SP_CURRENT_THEME", $theme);
		
		if (is_file($template)) {
			return $template;
		}
		$depr       =   C('TMPL_FILE_DEPR');
		$template   =   str_replace(':', $depr, $template);
		
		// 获取当前模块
		$module = MODULE_NAME;
		if (strpos($template,'@')) {                              // 跨模块调用模版文件
			list($module, $template) = explode('@', $template);
		}
		
		$module = $module . "/";
		
		// 分析模板文件规则，如果模板文件名为空 按照默认规则定位
		if ('' == $template) {
			$template = CONTROLLER_NAME . $depr . ACTION_NAME;
		} elseif (false === strpos($template, '/')) {
			$template = CONTROLLER_NAME . $depr . $template;
		}
		
		$file = addTemplateFileSuffix($current_tmpl_path . $module . $template);
		$file = str_replace("//", '/', $file);
		if (!file_exists_case($file)) {
		    E(L('_TEMPLATE_NOT_EXIST_') . ':' . $file);
		}
		return $file;
	}
	
	/**
	 * 设置错误、成功跳转界面
	 */
	private function _setActionSuccessErrorTpl() {
		// $tplPath
		$theme = C('SP_DEFAULT_THEME');
		if (C('TMPL_DETECT_THEME') && cookie('think_template')) {					// 自动侦测模板主题
			$theme = cookie('think_template');
		}
		$tplPath = C("SP_TMPL_PATH") . $theme . "/";
		
		// $defaultJump
		$defaultJump = THINK_PATH . 'Tpl/dispatch_jump.tpl';

		$actionSuccess = addTemplateFileSuffix($tplPath . C("SP_TMPL_ACTION_SUCCESS"));
		if (file_exists_case($actionSuccess)) {
			C("TMPL_ACTION_SUCCESS", $actionSuccess);
		} else {
			C("TMPL_ACTION_SUCCESS", $defaultJump);
		}

		$actionError = addTemplateFileSuffix($tplPath . C("SP_TMPL_ACTION_ERROR"));
		if (file_exists_case($actionError)) {
			C("TMPL_ACTION_ERROR", $actionError);
		} else {
			C("TMPL_ACTION_ERROR", $defaultJump);
		}
	}
	
}